package com.snow.useviewdemo.function.systems;

import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.util.Log;

import com.snow.useviewdemo.APPApplication;
import com.snow.useviewdemo.MainActivity;
import com.snow.useviewdemo.R;
import com.snow.useviewdemo.base.BaseActivity;
import com.snow.useviewdemo.databinding.ActGetTopRunningBinding;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import me.jessyan.autosize.utils.LogUtils;

/**
 * Created by zhaoyingtao
 * Date: 2020/6/15
 * Describe: 获取运行前台的Activity及应用包名
 */
public class GetTopRuningActivity extends BaseActivity<ActGetTopRunningBinding> {
    @Override
    protected int getLayoutId() {
        return R.layout.act_get_top_running;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isUseGranted()) {
            Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
        Log.e("snow", "======" + isUseGranted());
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case 1001:
//                    getaaa();
                    //需要权限，并且不能手动获取
                    String adbResult = javaAdb("dumpsys window | findstr mCurrentFocus");
//                   String adbResult =  javaAdb("pm list packages -3");///不需要权限可以获取
                    Log.e("snow", "adbResult=================" + adbResult);
                    getTaskPackname(GetTopRuningActivity.this);
                    handler.sendEmptyMessageDelayed(1001, 3000);
                    break;
            }
            return false;
        }
    });

    @Override
    protected void setViewData(Bundle savedInstanceState) {
        handler.sendEmptyMessage(1001);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

    private boolean isUseGranted() {
        Context appContext = APPApplication.getInstance();
        AppOpsManager appOps = (AppOpsManager) appContext
                .getSystemService(Context.APP_OPS_SERVICE);
        int mode = -1;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            mode = appOps.checkOpNoThrow("android:get_usage_stats",
                    android.os.Process.myUid(), appContext.getPackageName());
        }
        boolean granted = mode == AppOpsManager.MODE_ALLOWED;
        return granted;
    }

    public static String getTaskPackname(Context context) {
        String currentApp = "CurrentNULL";
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
            long time = System.currentTimeMillis();
            List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
            if (appList != null && appList.size() > 0) {
                SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
                for (UsageStats usageStats : appList) {
                    mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
                }
                if (mySortedMap != null && !mySortedMap.isEmpty()) {
                    currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
                }
            }
        } else {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
            currentApp = tasks.get(0).processName;
        }
        Log.e("snow", "Current App in foreground is: " + currentApp);
        return currentApp;
    }

    /**
     * 执行adb命令
     *
     * @param adbCmd 命令，原命令adb shell pm list packages -3   只需传 pm list packages -3即可（不要传adb shell）
     *               有root权限，有些命令会报：Permission Denial: can't dump WindowManager from from pid=9486, uid=10035
     *               无root权限，有些命令不报错，但会返回""
     *               有些命令无论有无root权限，都可以执行成功
     * @return
     */
    private String javaAdb(String adbCmd) {
        BufferedReader reader = null;
        String content = "";
        try {
            Process process = Runtime.getRuntime().exec(adbCmd);
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuffer output = new StringBuffer();
            int read;
            char[] buffer = new char[4096];
            while ((read = reader.read(buffer)) > 0) {
                output.append(buffer, 0, read);
            }
            reader.close();
            content = output.toString();
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("snow", "adb執行报错=====" + e.getMessage());
        }
        return content;
    }

    private void getaaa() {
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTasks = am.getRunningTasks(10);
        List<ActivityManager.RunningAppProcessInfo> infoList = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo info : infoList) {
            //进程名称
            String processName = info.processName;
            //进程的重要程度(越低越重要)
            int importance = info.importance;
            Log.e("snow", "进程名称=====" + processName);
        }
        Log.e("snow", "infoList.size()=====" + infoList.size());
        Log.e("snow", "==============runningTasks.size()=====" + runningTasks.size());
    }
}
